package com.hua.io.old;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: _hua
 * @created: 2019/3/17.
 * @updater:
 * @description:
 */
public class ThreadPoolServer {
    public static void main(String args[]){
        ExecutorService executorService= Executors.newFixedThreadPool(5);
        try {
            ServerSocket serverSocket = new ServerSocket(7700);
            while (true)
            {
                Socket client = serverSocket.accept();
                System.out.println("新增连接："+client.getInetAddress()+":"+client.getPort());
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        handleReq(client);
                    }
                });
                executorService.shutdown();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleReq(Socket client) {
        System.out.println("处理客户端请求"+client.toString());
        try {
            InputStream inputStream = client.getInputStream();
            byte[] b = new byte[1024];
            int len =inputStream.read(b);
           /* if(len==-1){
                continue;
            }*/
            String msg = new String(b,0,len);
            System.out.println("收到客户端的数据========="+msg);

            OutputStream outputStream=client.getOutputStream();
            outputStream.write(("服务器已收到数据"+msg).getBytes());
            outputStream.flush();

            System.out.println("返回========="+msg);
            //client.shutdownInput();
            //client.shutdownOutput();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
